package com.lxq.blog.com.lxq.blog.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {
    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
                                        Authentication authentication) throws IOException {
//        httpServletResponse.setContentType("application/json;charset=utf-8");
//        System.out.println("onAuthenticationSuccess");
        httpServletResponse.setContentType(MediaType.APPLICATION_JSON_VALUE);
        var savedRequest = new HttpSessionRequestCache().getRequest(httpServletRequest, httpServletResponse);
        var beforeUrl = "index.html";
        if (savedRequest != null) {
            beforeUrl = savedRequest.getRedirectUrl();
        }
        //System.out.println("被拦截的地址："+beforeUrlTest);
        ObjectMapper mapper = new ObjectMapper();
        ObjectNode echo = mapper.createObjectNode();
        echo.put("code", true);
        echo.put("result", "登录成功");
        echo.put("redirectUrl", beforeUrl);
        httpServletResponse.getWriter().write(echo.toString());
        httpServletResponse.getWriter().flush();
        httpServletResponse.getWriter().close();
        var userId = httpServletRequest.getParameter("userId");
        var session = httpServletRequest.getSession();
        session.setAttribute(session.getId(), userId);
    }
}
